import {Store} from 'iflux2';
import {fromJS, List} from 'immutable';

import GoodsActor from './actor/goods-actor';
import GoodsAddActor from './actor/goods-add-actor';
import webApi from './webapi';

import {GoodsAddedType, GoodsSortType} from './constant/action-type';

import {message} from 'antd';

export default class AppStore extends Store{

    bindActor() {
        return [
            new GoodsActor,
            new GoodsAddActor
        ];
    }


    getGoodsDisplay = async ()=>{
        try {
            const {status, ...rest} = await webApi.getGoodsDisplay();
            this.dispatch(GoodsSortType.SET_SORT_TYPE, status);
        } catch(err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }


    /**
     * 查询排序商品列表
     * @returns {Promise.<void>}
     */
    querySortGoods = async ()=>{
        const allState = this.state();

        try {
            const {dataList, ...res} = await webApi.querySortGoods();
            this.dispatch(GoodsSortType.SET_LIST, fromJS(dataList));
        } catch (err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }



    /**
     * 商品排序
     */
    setGoodsSort = async (goodsList)=>{
        this.dispatch(GoodsSortType.SET_LIST, fromJS(goodsList));
        //缺少后台交互
        const allState = this.state();

        const d2cGoodsSorts = allState.get('goodsList').map((goods, index)=>{
            return {
                productId: goods.get('productId'),
                goodsId: goods.get('goodsId'),
                sort: index
            }
        }).toJS();

        try {
            await webApi.setGoodsSort({d2cGoodsSorts})
        } catch(err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }


    /**
     * 删除排序商品
     * @param goods
     * @returns {Promise.<void>}
     */
    delGoods = async (goods) => {
        this.dispatch('DEL_GOODS', fromJS(goods));

        try {
            await webApi.delSortGoods(goods);
            message.success('删除成功，若数据未同步，请稍后手动刷新', 1.5);
        } catch(err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    };




    ///////////////////////////////////////////**** 添加排序商品操作 ***///////////////////////////////////////////////////////
    /**
     * 设置关键字
     * @param keyWords
     */
    setKeyWords = (keyWords) => {
        this.dispatch(GoodsAddedType.SET_KEYWORDS, keyWords);
    };


    /**
     * 关键字
     * @returns {Promise.<void>}
     */
    onSearch = () => {
        this.dispatch(GoodsAddedType.RESET_PAGINATION);
        return this.queryGoodsAdded();
    };


    /**
     * 分页查询
     * @param page
     * @returns {Promise.<void>}
     */
    changePage = (page) => {
        this.dispatch(GoodsAddedType.SET_PAGINATION, fromJS(page));
        return this.queryGoodsAdded();
    };

    resetPagination = ()=>{
        this.dispatch(GoodsAddedType.RESET_PAGINATION);
    }


    /**
     * 选择列操作
     * @param rowKeys
     */
    setSelected = (rowKeys) => {
        this.dispatch(GoodsAddedType.SET_SELECTED_KEYS, rowKeys);
    }


    /**
     * 查询商品
     * @returns {Promise.<void>}
     */
    queryGoodsAdded = async () => {
        const allState = this.state();

        const params = {
            showSortProduct: 0,
            keywords: allState.get('keyWords'),
            pageNum: allState.getIn(['pagination', 'pageNum']) - 1,
            pageSize: allState.getIn(['pagination', 'pageSize'])
        };

        try {
            const {dataList, ...rest} = await webApi.querySortGoods(params);
            this.dispatch(GoodsAddedType.SET_LIST, fromJS(dataList));
            rest.pageNum += 1;
            this.dispatch(GoodsAddedType.SET_PAGINATION, fromJS(rest));
            this.dispatch(GoodsAddedType.RESET_SELECTED_KEYS);
        } catch(err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }


    mergeAddedToSort = async () => {
        const allState = this.state();
        const goodsAddedList = allState.get('goodsAddedList');
        const selectedRowKeys = allState.get('selectedRowKeys');

        let addGoodsList =  goodsAddedList.filter(goods=>selectedRowKeys.has(goods.get(!allState.get('type') ? 'goodsId' : 'productId')));

        this.dispatch(GoodsSortType.SET_LIST, allState.get('goodsList').concat(addGoodsList));

        let d2cGoodsSorts = allState.get('goodsList').concat(addGoodsList).map((goods, index)=>{
            return {
                productId: goods.get('productId'),
                goodsId: goods.get('goodsId'),
                sort: index
            }
        }).toArray();

        try {
            await webApi.setGoodsSort({
                sortType: 1,
                d2cGoodsSorts
            });

            message.success('保存成功，若数据未同步，请稍后手动刷新', 1.5);
        } catch(err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    };


    resetRowKeys = () => {
        this.dispatch(GoodsAddedType.RESET_SELECTED_KEYS);
    }
}